package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.MapConstant;
import com.tbit.uqbike.client.constant.MemberCardConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.constant.SysConstant;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.vo.JsonResult;
import com.tbit.uqbike.client.pojo.vo.VipLogDot;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子围栏
 *
 * @author Leon
 * 2019年8月28日 下午1:53:08
 */
@Controller
@RequestMapping("/geo")
public class GeoController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private GeoService geoService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private AdAccountFeeService adAccountFeeService;
    @Autowired
    private MachineBorrowService machineBorrowService;
    @Autowired
    private VipCardLogService vipCardLogService;
    @Autowired
    private VipFeeService vipFeeService;
    @Autowired
    private CacheService cacheService;


    /**
     * 查询附近的电子围栏
     *
     * @param token      令牌
     * @param accountId  品牌id
     * @param lo         经度
     * @param la         纬度
     * @param toMapType  返回地图类型
     * @param getMapType 请求地图类型
     * @param radius     半径
     * @param response   响应
     * @ignoreParams request
     */
    @RequestMapping("/find")
    public void find(String token, Integer accountId, Double lo, Double la, Integer toMapType, Integer getMapType, Integer radius,
                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = null;
            if (token != null && !token.equals("")) {
                user = tokenService.getUser(token);
            }

            Assert.notNull(lo, "-2001", "经度不能为空");
            Assert.notNull(la, "-2002", "纬度不能为空");

            /*校准百度经纬度为原始经纬度*/
            Point point = new Point(lo, la);
            if (toMapType != null) {
                point = calibrateService.calibrate(point, toMapType, SysConstant.ORIGINAL);
            }
            List<Geo> geos = geoService.findNearGeo(user, point, getMapType, radius, accountId);

            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, geos);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 获取电子围栏 正在使用
     *
     * @param accountId 品牌id
     * @param lo        经度
     * @param la        纬度
     * @param mapType   地图类型
     * @param geoId     电子围栏id
     * @param response  响应
     * @ignoreParams request
     */
    @RequestMapping("/getInGeo")
    public void getInGeo(Integer accountId, Integer adAccountId, Double lo, Double la, String token, Integer mapType, Integer geoId,
                         HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            Assert.notNull(accountId, "-10001", "品牌id不能为空");
            Assert.notNull(lo, "-2001", "经度不能为空");
            Assert.notNull(la, "-2002", "纬度不能为空");

            if (mapType == null) {
                mapType = MapConstant.MAP_GOOGLE;
            }
            /**如果用户登录借车，只展示所接车辆运营区域*/
            if (token != null) {
                User user = tokenService.getUser(token);
                if (user != null) {
                    MachineBorrow machineBorrow = machineBorrowService.getByUserId(user.getUserId());
                    if (machineBorrow != null) {
                        Machine machine = machineService.getByMachineId(machineBorrow.getMachineId());
                        adAccountId = machine.getAccountId();
                    }
                }
            }
            Geo geo = null;
            if (adAccountId != null) {
                List<Geo> list = geoService.getByAccountId(adAccountId);
                if (list.size() > 0) {
                    geo = list.get(0);
                }
            } else {
                /*校准经纬度为原始经纬度*/
                Point point = new Point(lo, la);
                point = calibrateService.calibrate(point, mapType, SysConstant.ORIGINAL);

                geo = geoService.getByBrandId(accountId, point);

                if (geoId != null && geo != null && geoId.equals(geo.getGeoId())) {
                    geo = null;
                }
            }

            if (geo != null) {
                calibrateService.calGeo(geo, MapConstant.MAP_ORI, mapType);
                //3.1.2需求，向前端返回静止临时停车时间和静止结束订单时间
                AccountConfig accountConfig = cacheService.getConfig(adAccountId);
                Integer stopTime = accountConfig == null ? null : accountConfig.getStopTime();
                Integer finishTime = accountConfig == null ? null : accountConfig.getFinishTime();
                if (stopTime != null) {
                    geo.setStopTime(stopTime);
                }
                if (finishTime != null) {
                    geo.setFinishTime(finishTime);
                }
                //4.1.1需求，向前端返回自动结束订单开关
                geo.setFinishOrderSwitch(accountConfig == null ? null : accountConfig.getFinishOrderSwitch());
            }


            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, geo);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 通过设备编号获取
     *
     * @param token     令牌
     * @param machineNO 设备编号
     * @param mapType   地图类型
     * @param response  响应
     * @ignoreParams request
     */
    @RequestMapping("/getByMachineNO")
    public void getByMachineNO(String token, String machineNO, Integer mapType,
                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */
            Assert.hasLength(machineNO, "-30001", "machineNO不能为空");

            if (mapType == null) {
                mapType = MapConstant.MAP_GOOGLE;
            }

            Machine machine = machineService.getByUserCode(machineNO);
            if (machine == null) {
                throw new BaseException("-30005", "该编号不存在");
            }

            /**查询电子围栏*/
            List<Geo> geos = geoService.getByAccountId(machine.getAccountId());
            if (geos.size() > 0) {
                Geo geo = geos.get(0);
                calibrateService.calGeo(geo, MapConstant.MAP_ORI, mapType);
                map.put("geo", geo);
            }
            User user = tokenService.getUser(token);
            /**查询调度*/
            AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(machine.getAccountId(), machine.getMachineId());
            AdAccountFee vipFee = null;
            Integer feeId = 0;
            if (adAccountFee != null && adAccountFee.getName() != null) {
                feeId = adAccountFee.getFeeId();
            }
            /**查询用户购买的会员卡*/
            VipLogDot vipLogDot = vipCardLogService.getUserVip(machine.getAccountId(), user.getUserId(), feeId);
            if (vipLogDot != null && vipLogDot.getVipType().equals(MemberCardConstant.VIP_CARD_VIPFEE)) {
                vipFee = vipFeeService.getByVipId(vipLogDot.getVipId());
            }
            if (vipFee != null) {
                adAccountFee = vipFee;
            }
            if (adAccountFee != null) {
                map.put("adAccountFee", adAccountFee);
            }

            map.put(ResponseCode.RET, ResponseCode.SUCC);

        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


    //获取运营区域
    @RequestMapping("/getByAccount")
    public JsonResult getByAccount(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer mapType, HttpServletRequest request) {
        if (mapType == null) {
            mapType = MapConstant.MAP_GOOGLE;
        }
        List<Geo> geoList = geoService.getByAccountId(accountId);
        return JsonResult.succ(geoList);
    }

}
